/*
 * Copyright 2000-2009 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.jetbrains.idea.maven.dom.converters

import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.text.VersionComparatorUtil
import com.intellij.util.xml.ConvertContext
import org.jetbrains.idea.maven.dom.converters.MavenConsumerPomUtil.getParentVersionForConsumerPom
import org.jetbrains.idea.maven.dom.converters.MavenConsumerPomUtil.isConsumerPomResolutionApplicable
import org.jetbrains.idea.maven.indices.MavenProjectIndicesManager
import org.jetbrains.idea.maven.model.MavenId
import org.jetbrains.idea.maven.project.MavenWorkspaceSettingsComponent
import org.jetbrains.idea.maven.utils.MavenUtil
import org.jetbrains.idea.reposearch.DependencySearchService
import java.util.regex.Pattern

class MavenArtifactCoordinatesVersionConverter : MavenArtifactCoordinatesConverter() {
  override fun fromString(s: String?, context: ConvertContext): String? {
    if (s != null) {
      return super.fromString(s, context)
    }

    if (isConsumerPomResolutionApplicable(context.project)) {
      return getParentVersionForConsumerPom(context)
    }
    return null
  }


  override fun doIsValid(id: MavenId, manager: MavenProjectIndicesManager, context: ConvertContext): Boolean {
    if (StringUtil.isEmpty(id.groupId) || StringUtil.isEmpty(id.artifactId)) {
      return false
    }

    val mavenVersion = MavenUtil.getMavenVersion(
      MavenWorkspaceSettingsComponent.getInstance(context.project).settings.generalSettings.effectiveMavenHome)
    if (VersionComparatorUtil.compare(mavenVersion, "3.6.3") <= 0 && id.version == null) {
      return false
    }

    if (id.version == null) {
      return getParentVersionForConsumerPom(context) != null
    }

    if (id.version!!.isBlank()) {
      return false
    }

    return if (MAGIC_VERSION_PATTERN.matcher(id.version!!).matches()) true
    else manager.hasVersion(id.groupId, id.artifactId, id.version) // todo handle ranges more sensibly
  }

  override fun doGetVariants(id: MavenId, searchService: DependencySearchService): Set<String> {
    // Do nothing. Completion variants are generated by MavenVersionCompletionContributor.
    return emptySet()
  }

  companion object {
    private val MAGIC_VERSION_PATTERN = Pattern.compile(
      "\\s*(?:LATEST|RELEASE|[(\\[].*|.*-20\\d{6}\\.[0-2]\\d{5}-\\d+)\\s*")
  }
}